package starfield;

import starfield.util.JSONUtils;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

public class Configuration {
	public static final String CONFIGURATION_FILENAME = "starfield.config";
	
	private static final String KEY_STARBOUND_PATH = "starboundPath";
	
    private static String starboundPath;
	
	public static String getConfigurationFilePath() {
		return System.getProperty("user.dir") + File.separator + CONFIGURATION_FILENAME;
	}
	
	public static boolean isValid() {
		return isStarboundPathValid(starboundPath);
	}
    
    public static boolean isStarboundPathValid(String path) {
		if (path == null) {
            return false;
        } else {
            File directory = new File(path);

            if (directory.exists() && directory.isDirectory()) {
                File assetsDirectory = new File(path + File.separator + Application.VANILLA_ASSETS_FOLDER);
                return assetsDirectory.exists() && assetsDirectory.isDirectory();
            } else {
                return false;
            }
        }
    }

	public static String getStarboundPath() {
		return starboundPath;
	}

	public static void setStarboundPath(String starboundPath) {
		Configuration.starboundPath = starboundPath;
	}
	
	public static void save() throws IOException {	
		FileUtils.writeStringToFile(new File(getConfigurationFilePath()), serialize().toJSONString());
	}

	public static boolean load() {
		try {
			String json = FileUtils.readFileToString(new File(getConfigurationFilePath()));
			deserialize(json);
			return true;
		} catch (IOException | ParsingException ex) {
			return false;
		}
	}
	
	protected static void deserialize(String json) throws ParsingException {
		Object parsedJson = JSONValue.parse(json);

		if (parsedJson instanceof JSONObject) {
			JSONObject configJson = (JSONObject)parsedJson;

			if (configJson.containsKey(KEY_STARBOUND_PATH)) {
				starboundPath = JSONUtils.getString(configJson, KEY_STARBOUND_PATH);
			} else {
				throw new ParsingException("Missing Starbound path.");
			}
		} else {
			throw new ParsingException("Root of JSON must be object.");
		}
	}
	
	protected static JSONObject serialize() {
		JSONObject configJson = new JSONObject();
		
		configJson.put(KEY_STARBOUND_PATH, starboundPath);
		
		return configJson;
	}
}